package memento.test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MementoCaretaker {
	private final List<UserInfo.Memento> mementoHistory;
	private final Map<String, UserInfo.Memento> namedMementos;
	private int currentIndex;
	private final int maxHistorySize;

	public MementoCaretaker() {
		this(10); // 默认保存10个历史状态
	}

	public MementoCaretaker(int maxHistorySize) {
		this.maxHistorySize = maxHistorySize;
		this.mementoHistory = new ArrayList<>();
		this.namedMementos = new HashMap<>();
		this.currentIndex = -1;
	}

	// === 保存状态 ===
	public void saveState(UserInfo.Memento memento) {
		if (memento == null) {
			throw new IllegalArgumentException("备忘录不能为空");
		}

		// 如果当前不在历史末尾，删除后续历史
		if (currentIndex < mementoHistory.size() - 1) {
			mementoHistory.subList(currentIndex + 1, mementoHistory.size()).clear();
		}

		// 添加新状态
		mementoHistory.add(memento);
		currentIndex++;

		// 控制历史大小
		if (mementoHistory.size() > maxHistorySize) {
			mementoHistory.remove(0);
			currentIndex--;
		}

		System.out.println("✅ 已保存状态：" + memento.getDescription());
	}

	// === 撤销（返回上一状态） ===
	public UserInfo.Memento undo() {
		if (!canUndo()) {
			throw new IllegalStateException("没有可撤销的状态");
		}

		currentIndex--;
		UserInfo.Memento memento = mementoHistory.get(currentIndex);
		System.out.println("↶ 撤销到：" + memento.getDescription());
		return memento;
	}

	// === 重做（前进到下一状态） ===
	public UserInfo.Memento redo() {
		if (!canRedo()) {
			throw new IllegalStateException("没有可重做的状态");
		}

		currentIndex++;
		UserInfo.Memento memento = mementoHistory.get(currentIndex);
		System.out.println("↷ 重做到：" + memento.getDescription());
		return memento;
	}

	// === 状态检查 ===
	public boolean canUndo() {
		return currentIndex > 0;
	}

	public boolean canRedo() {
		return currentIndex < mementoHistory.size() - 1;
	}

	// === 命名保存点 ===
	public void saveNamedState(String name, UserInfo.Memento memento) {
		namedMementos.put(name, memento);
		System.out.println("💾 已保存命名状态：" + name);
	}

	public UserInfo.Memento getNamedState(String name) {
		UserInfo.Memento memento = namedMementos.get(name);
		if (memento == null) {
			throw new IllegalArgumentException("未找到命名状态：" + name);
		}
		return memento;
	}

	// === 历史管理 ===
	public void showHistory() {
		System.out.println("=== 历史状态 ===");
		for (int i = 0; i < mementoHistory.size(); i++) {
			String marker = (i == currentIndex) ? " -> " : "    ";
			System.out.println(marker + i + ". " + mementoHistory.get(i));
		}

		if (!namedMementos.isEmpty()) {
			System.out.println("=== 命名状态 ===");
			namedMementos.forEach((name, memento) ->
					System.out.println("    " + name + ": " + memento));
		}
	}

	public void clearHistory() {
		mementoHistory.clear();
		namedMementos.clear();
		currentIndex = -1;
		System.out.println("🗑️ 已清空所有历史状态");
	}

	public int getHistorySize() {
		return mementoHistory.size();
	}

	public int getCurrentIndex() {
		return currentIndex;
	}
}